package com.atguigu.spzx.manager.controller;

import com.atguigu.exception.LoginException;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.pojo.system.SysUser;
import com.atguigu.spzx.model.pojo.system.SysUserAuthContextUtil;
import com.atguigu.spzx.model.request.system.LoginRequest;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.SysMenuVo;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.utils.DYLAssert;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author dyl
 * @version 1.0
 * @description:
 * @date 2024/12/24 19:47
 */
@RestController
@RequestMapping("/admin/system/index")
@Tag(name = "登录接口")
@CrossOrigin(allowCredentials = "true", originPatterns = "*", allowedHeaders = "*")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result<LoginVo> login(@RequestBody LoginRequest loginRequest) throws LoginException {
        return sysUserService.doLogin(loginRequest);
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取登录用户信息")
    public Result<SysUser> getInfo(@RequestHeader("token") String token) throws LoginException {
//        SysUser userInfo = sysUserService.getUserInfo(token);
        SysUser user = SysUserAuthContextUtil.get();
        DYLAssert.notNull(user, "获取用户信息失败");
        return Result.ok(user);
    }

    @GetMapping("/generateValidateCode")
    @Operation(summary = "获取验证码")
    public Result<ValidateCodeVo> generateValidateCode() {
        return Result.ok(sysUserService.generateValidateCode());
    }

    @DeleteMapping("/logout")
    @Operation(summary = "退出登录")
    public Result logout(@RequestHeader("token") String token) {
        sysUserService.doLogout(token);
        return Result.ok();
    }

    @GetMapping("/menus")
    @Operation(summary = "获取动态路由")
    public Result<List<SysMenuVo>> menus() {
        SysUser user = SysUserAuthContextUtil.get();
        List<SysMenuVo> results =  sysMenuService.getMenuVoByUserId(user.getId());
        return Result.ok(results);
    }
}
